package net.qdd.framework.mybatis.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import net.qdd.framework.mybatis.service.BaseService;
import net.qdd.framework.common.utils.PageResult;
import net.qdd.framework.common.query.Query;
import cn.hutool.core.util.StrUtil;

/**
 * 基础服务实现类
 * 
 * @param <M> Mapper类型
 * @param <T> 实体类型
 */
public class BaseServiceImpl<M extends BaseMapper<T>, T> extends ServiceImpl<M, T> implements BaseService<T> {

    @Override
    public PageResult<T> page(Query query) {
        IPage<T> page = new Page<>(query.getCurrent(), query.getSize());
        QueryWrapper<T> wrapper = new QueryWrapper<>();
        
        // 处理排序
        if (StrUtil.isNotBlank(query.getOrder())) {
            if ("asc".equalsIgnoreCase(query.getAsc())) {
                wrapper.orderByAsc(query.getOrder());
            } else {
                wrapper.orderByDesc(query.getOrder());
            }
        }
        
        page = this.page(page, wrapper);
        return new PageResult<>(page.getRecords(), page.getTotal());
    }

    /**
     * 获取分页对象
     * @param query 查询条件
     * @return 分页对象
     */
    protected IPage<T> getPage(Query query) {
        return new Page<>(query.getCurrent(), query.getSize());
    }

    /**
     * 获取查询包装器
     * @param query 查询条件
     * @return 查询包装器
     */
    protected QueryWrapper<T> getWrapper(Query query) {
        QueryWrapper<T> wrapper = new QueryWrapper<>();
        
        // 处理排序
        if (StrUtil.isNotBlank(query.getOrder())) {
            if ("asc".equalsIgnoreCase(query.getAsc())) {
                wrapper.orderByAsc(query.getOrder());
            } else {
                wrapper.orderByDesc(query.getOrder());
            }
        }
        
        return wrapper;
    }
}
